package cn.antho.org.controller;

import cn.antho.basic.anno.PreAuthorize;
import cn.antho.basic.util.AjaxResult;
import cn.antho.basic.util.LoginContext;
import cn.antho.basic.util.PageList;
import cn.antho.org.domain.Employee;
import cn.antho.org.query.EmployeeQuery;
import cn.antho.org.service.IEmployeeService;
import cn.antho.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/emp")
@PreAuthorize
public class EmployeeController {

    @Autowired
    private IEmployeeService IEmployeeService;

    // 增 or 改
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee) {
        if (null == employee.getId()) {
            // 增
            IEmployeeService.add(employee);
        } else {
            // 改
            IEmployeeService.update(employee);
        }
        return AjaxResult.me().success();
    }

    // 删
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "根据id删除", sn = "emp:delete")
    public AjaxResult delete(@PathVariable("id") Long id) {
        IEmployeeService.delete(id);
        return AjaxResult.me().success();
    }

    // 查所有
    @GetMapping
    public List<Employee> findAll() {
        return IEmployeeService.findAll();
    }

    // 查单个
    @GetMapping("/{id}")
    @PreAuthorize(name = "根据id查询员工",sn = "emp:findById")
    public Employee findById(@PathVariable("id") Long id) {
        return IEmployeeService.findById(id);
    }

    // 分页查询
    @PostMapping
    @PreAuthorize(name = "分页查询员工",sn = "emp:queryByPage")
    public PageList<Employee> queryByPage(@RequestBody EmployeeQuery query) {
        return IEmployeeService.queryByPage(query);
    }

    @PatchMapping
    @PreAuthorize(name = "批量删除员工",sn = "emp:batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids) {
        IEmployeeService.batchDel(ids);
        return AjaxResult.me().success();
    }

    @GetMapping("/emplist")
    public List<Employee> queryByShopId(HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Long shopId = IEmployeeService.findByLogininfoId(logininfo.getId()).getShopId();
        return IEmployeeService.queryByShopId(shopId);

    }
}
